package org.example.springcloud.controller;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.example.springcloud.entities.Payment;
import org.example.springcloud.lb.LoadBalancer;
import org.example.springcloud.result.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author Jandmla
 * Date: 2022/7/22
 * Time: 15:34
 * Description:
 */
@RestController
@Slf4j
public class OrderControllerImpl implements OrderController{

    /**
     * 单机版可以直接指定URL，但是集群是需要动态改变，因此不使用
     */
    @Deprecated
    public static final String PATH_URL = "http://localhost:8001";

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";


    @Resource
    private DiscoveryClient discoveryClient;

    private final RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    public OrderControllerImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 负载均衡算法测试接口
     * @return 测试结果
     */
    @GetMapping(value = "consumer/payment/lb")
    public CommonResult paymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        return restTemplate.postForObject(serviceInstance.getUri()+"/payment/lb",null,CommonResult.class);
    }

    /**
     * 数据插入
     * @param payment 数据实体
     * @return 插入结果
     */
    @Override
    @PostMapping(value = "consumer/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    /**
     * 数据获取
     * @param id ID
     * @return 查询结果
     */
    @Override
    @GetMapping(value = "consumer/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    /**
     * 练习 RestTemplate 获取entity方法
     * @param id 参数ID
     * @return 查询结果
     */
    @GetMapping(value = "consumer/payment/getEntity/{id}")
    public CommonResult getEntity(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }else {
            return new CommonResult<>(500,"操作失败！"+entity.getStatusCode());
        }
    }
}